import base64
import re
import os
import urllib 

def word2pdf(name):
		os.system("unoconv -f pdf files/" + name)
		os.system("mv files/" + name.split(".")[0] + ".pdf" + " pdf/")

def ppt2pdf(name):
		os.system("libreoffice3.6 --headless --invisible --convert-to pdf files/" + name)
		os.system("mv " + name.split(".")[0] + ".pdf" + " pdf/")

def code2png(name):
	        item = name.split(".")[0]
		os.system("mkdir pic/" + item)
        	os.system("pygmentize -f png -O full,encoding=utf8 -o pic/" + item + "/" + item  + ".png " + "files/" + name)
		os.system("mkdir log/" + item)
		f1 = open("pic/" + item + "/" + item + ".png",'rb')
                f2 = file("log/" + item + "/" + item + ".log",'w')
                width, height = re.search(r'PNG (\d+)x(\d+) ',os.popen('identify '+"pic/" + item + "/" + item + ".png").read()).groups()
		string = base64.b64encode(f1.read())
                f2.write(string)
		base = []
		base.append([string,int(width)/2,int(height)/2])
                f1.close()
                f2.close()
		return base

def pdf2base64(name):
	item = name.split(".")[0]
	os.system("mkdir pic/" + item)
	os.system("convert -density 200 pdf/" + item + ".pdf pic/" + item + "/" + item + ".png")
        number = os.popen("pdfinfo pdf/"+ item + ".pdf|grep Pages").readlines()[0]
	os.system("mkdir log/" + item)
        p = re.compile(r'\d+')
        number = int(p.findall(number)[0])
        item = item + "-"
	base = []
        for i in range(number):
                f1 = open("pic/" + item[:-1] + "/" + item + str(i) + ".png",'rb')
                f2 = file("log/" + item[:-1] + "/" + item + str(i) + ".log",'w')
                width, height = re.search(r'PNG (\d+)x(\d+) ',os.popen('identify '+"pic/" + item[:-1] + "/" + item + str(i) + ".png").read()).groups()
		string = base64.b64encode(f1.read())
                f2.write(string)
		base.append([string,int(width)/4,int(height)/4])
                f1.close()
                f2.close()
	return base

def trans2base64(item):
	if (item.find(".pdf") >= 0):
		os.system("cp files/" + item + " pdf/" + item)
		return pdf2base64(item);
	elif ((item.find(".doc") >= 0) | (item.find(".docx") >= 0)):
#		try:
			word2pdf(item)
			return pdf2base64(item)
#		except:
#			print "ERROR!"
	elif ((item.find(".ppt") >= 0) | (item.find(".pptx") >= 0)):
#		try:
			ppt2pdf(item)
			return pdf2base64(item)
#		except:
#			print "ERROR!"
	else:
#		try:
			return code2png(item)
#		except:
#			print "Error!"


